"""
订单管理API路由
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from loguru import logger

from app.core.deps import get_db, get_current_user
from app.models.user import User
from app.services.tools import (
    search_order,
    get_user_orders,
    track_logistics,
    create_refund_request,
)


router = APIRouter()


# ==================== Pydantic模型 ====================

class OrderQueryResponse(BaseModel):
    """订单查询响应"""
    success: bool
    order: Optional[dict] = None
    message: Optional[str] = None


class OrderListResponse(BaseModel):
    """订单列表响应"""
    success: bool
    orders: list
    total: int


class LogisticsResponse(BaseModel):
    """物流查询响应"""
    success: bool
    logistics: Optional[dict] = None
    message: Optional[str] = None


class RefundRequest(BaseModel):
    """退款申请请求"""
    order_sn: str = Field(..., description="订单号")
    reason: str = Field(..., description="退款原因", min_length=5, max_length=500)


class RefundResponse(BaseModel):
    """退款申请响应"""
    success: bool
    message: str
    refund_id: Optional[str] = None
    estimated_time: Optional[str] = None


# ==================== API路由 ====================

@router.get("/query/{order_sn}", response_model=OrderQueryResponse)
async def query_order(
    order_sn: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    查询订单详情
    
    根据订单号查询订单的详细信息
    """
    try:
        logger.info(f"查询订单 | 用户: {current_user.id} | 订单号: {order_sn}")
        
        order = await search_order(order_sn, db)
        
        if not order:
            return OrderQueryResponse(
                success=False,
                message="订单不存在或您无权查看该订单"
            )
        
        # TODO: 验证订单是否属于当前用户
        
        return OrderQueryResponse(
            success=True,
            order=order
        )
        
    except Exception as e:
        logger.error(f"查询订单失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"系统错误: {str(e)}"
        )


@router.get("/list", response_model=OrderListResponse)
async def list_orders(
    status_filter: Optional[str] = Query(None, alias="status", description="订单状态过滤"),
    limit: int = Query(10, ge=1, le=100, description="返回数量"),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    获取订单列表
    
    获取当前用户的订单列表，支持按状态过滤
    """
    try:
        logger.info(f"获取订单列表 | 用户: {current_user.id} | 状态: {status_filter}")
        
        orders = await get_user_orders(
            user_id=current_user.id,
            db=db,
            status=status_filter,
            limit=limit
        )
        
        return OrderListResponse(
            success=True,
            orders=orders,
            total=len(orders)
        )
        
    except Exception as e:
        logger.error(f"获取订单列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"系统错误: {str(e)}"
        )


@router.get("/logistics/{order_sn}", response_model=LogisticsResponse)
async def query_logistics(
    order_sn: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    查询物流信息
    
    根据订单号查询物流状态和配送进度
    """
    try:
        logger.info(f"查询物流 | 用户: {current_user.id} | 订单号: {order_sn}")
        
        logistics = await track_logistics(order_sn=order_sn, db=db)
        
        if not logistics:
            return LogisticsResponse(
                success=False,
                message="暂无物流信息"
            )
        
        return LogisticsResponse(
            success=True,
            logistics=logistics
        )
        
    except Exception as e:
        logger.error(f"查询物流失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"系统错误: {str(e)}"
        )


@router.post("/refund", response_model=RefundResponse)
async def apply_refund(
    request: RefundRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """
    申请退款
    
    为指定订单申请退款
    """
    try:
        logger.info(f"申请退款 | 用户: {current_user.id} | 订单号: {request.order_sn}")
        
        result = await create_refund_request(
            user_id=current_user.id,
            order_sn=request.order_sn,
            reason=request.reason,
            db=db
        )
        
        return RefundResponse(**result)
        
    except Exception as e:
        logger.error(f"申请退款失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"系统错误: {str(e)}"
        )

